﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace UserControlLib
{
    /// <summary>
    /// PointerClock.xaml 的交互逻辑
    /// </summary>
    public partial class PointerClock : UserControl
    {
        public PointerClock()
        {
            InitializeComponent();
            //创建定时器
            CreateTimer();

            this.imgBackground.Source = new BitmapImage(new Uri("pack://application:,,,/UserControlLib;component/Assets/Images/Clock.png"));
        }

        // 定义依赖属性
        public static readonly DependencyProperty BackgroundImageSourceProperty =
            DependencyProperty.Register("BackgroundImageSource", typeof(ImageSource), typeof(PointerClock),
                new PropertyMetadata(new BitmapImage(new Uri("pack://application:,,,/UserControlLib;component/Assets/Images/Clock.png")), OnBackgroundImageSourceChanged));

        // .NET 属性包装
        public ImageSource BackgroundImageSource
        {
            get { return (ImageSource)GetValue(BackgroundImageSourceProperty); }
            set { SetValue(BackgroundImageSourceProperty, value); }
        }

        private static void OnBackgroundImageSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var pointerClock = d as PointerClock;
            if (pointerClock != null)
            {
                pointerClock.UpdateBackgroundImage();
            }
        }

        private void UpdateBackgroundImage()
        {
            if (this.BackgroundImageSource != null)
            {
                // 更新背景图像
                this.imgBackground.Source = this.BackgroundImageSource;
            }
        }
        //UI异步更新
        private void CreateTimer()
        {
            #region 每秒定时器服务
            DispatcherTimer timer = new DispatcherTimer
            {
                Interval = new TimeSpan(0, 0, 0, 1, 0)
            };
            timer.Tick += DispatcherTimer_Tick;
            timer.Start();
            #endregion
        }

        private void DispatcherTimer_Tick(object sender, EventArgs e)
        { 
            // 更新时钟指针角度和时间值
            var now = DateTime.Now;
            secondPointer.Angle = now.Second * 6;
            minutePointer.Angle = now.Minute * 6;
            hourPointer.Angle = (now.Hour % 12) * 30 + now.Minute * 0.5;
            labTime.Content = now.ToString("HH:mm:ss");
        }
    }
}
